//
//  VRHistoryTaskViewController.m
//  VRFirefighting
//
//  Created by Veer on 2018/8/22.
//  Copyright © 2018年 Veer. All rights reserved.
//

#import "VRHistoryTaskViewController.h"

#import "VRChooseMonthView.h"
#import "XNoDataView.h"
#import "VRHistoryTaskCell.h"

#import "VRHistoryTaskModel.h"

@interface VRHistoryTaskViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) VRChooseMonthView *chooseDataView;
@property (nonatomic, strong) XNoDataView *nodataView;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *choseDateBtn;

@property (nonatomic, strong) NSMutableArray<VRHistoryTaskModel *> *recordModelArray;
@property (nonatomic, assign) NSInteger curSelectedIndex;

@property (nonatomic, copy) NSString *searchTime;
@property (nonatomic, assign) NSInteger currentPage;

@end

@implementation VRHistoryTaskViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = ScrollViewBgColor;
    self.title = @"历史任务";
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.recordModelArray = [NSMutableArray array];
    self.currentPage = 1;
    
    [self setupSubView];
    [self getRecordWithIsRemoveArray:YES];
    
    weakify(self)
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        strongify(self)
        if (self.searchTime.length > 0) {
            [self searchRecordWith:self.searchTime IsRemoveArray:NO];
        }else{
            [self getRecordWithIsRemoveArray:NO];
        }
    }];
}

- (void)setupSubView
{
    [self.view addSubview:self.tableView];
    
    UIView *headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT, kScreenWidth, 70);
    [self.view addSubview:headerView];
    
    // 按钮
    UIImageView *iconImgView = [[UIImageView alloc] init];
    iconImgView.image = [UIImage imageNamed:@"task_aa"];
    iconImgView.contentMode = UIViewContentModeScaleAspectFit;
    [headerView addSubview:iconImgView];
    [iconImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.centerY.mas_equalTo(headerView);
        make.width.mas_equalTo(18);
        make.height.mas_equalTo(18);
    }];
    
    UILabel *nameLbl = [[UILabel alloc] init];
    nameLbl.numberOfLines = 2;
    nameLbl.text = @"历史任务浏览";
    nameLbl.textColor = RGB(51, 51, 51);
    nameLbl.font = VRFont(16);
    nameLbl.frame = CGRectMake(CGRectGetMaxX(iconImgView.frame) + 4, 0, 150, 42);
    [headerView addSubview:nameLbl];
    [nameLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(iconImgView.mas_right).offset(4);
        make.centerY.mas_equalTo(headerView);
    }];
    
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.backgroundColor = MAINColor;
    [searchBtn setTitle:@"全部" forState:UIControlStateNormal];
    searchBtn.titleLabel.font = VRFont(16);
    [searchBtn setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
    [searchBtn setTitleColor:RGB(120, 120, 120) forState:UIControlStateHighlighted];
    [searchBtn addTarget:self action:@selector(onShowAllBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:searchBtn];
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20);
        make.centerY.mas_equalTo(headerView);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(30);
    }];
    
    XButton *choseDateBtn = [XButton buttonWithType:UIButtonTypeCustom];
    //    goCardPackageBtn.layer.cornerRadius = 2;
    //    goCardPackageBtn.layer.borderColor = RGB(248, 177, 90).CGColor;
    choseDateBtn.layer.borderColor = MAINColor.CGColor;
    choseDateBtn.layer.borderWidth = 1.0;
    [choseDateBtn setTitle:@"选择时间" forState:UIControlStateNormal];
    choseDateBtn.titleLabel.font = VRFont(14);
    [choseDateBtn setTitleColor:RGB(120, 120, 120) forState:UIControlStateNormal];
    [choseDateBtn setTitleColor:RGB(211, 209, 209) forState:UIControlStateDisabled];
    choseDateBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [choseDateBtn setImage:[UIImage imageNamed:@"shearch"] forState:UIControlStateNormal];
    choseDateBtn.imageEdgeInsets = UIEdgeInsetsMake(8, 0, 8, 0);
    [choseDateBtn addTarget:self action:@selector(onChoseDateBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:choseDateBtn];
    self.choseDateBtn = choseDateBtn;
    [choseDateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(searchBtn.mas_left).offset(-2);
        make.centerY.mas_equalTo(headerView);
        make.width.mas_equalTo(122);
        make.height.mas_equalTo(30);
    }];
    
    [nameLbl mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(choseDateBtn.mas_left).offset(-4);
    }];
}


#pragma mark - networking
- (void)getRecordWithIsRemoveArray:(BOOL)isRemoveArray
{
    if (isRemoveArray) {
        self.currentPage = 1;
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"UserID"] = [VRUser shareUser].token;
    param[@"page"] = @(self.currentPage++);
    //    param[@"fIsAreaManage"] = @([VRUser shareUser].fIsAreaManage);
    
    if (isRemoveArray) {
        [self.recordModelArray removeAllObjects];
    }
    weakify(self)
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    [JKNetworking postWithSign:GetHistoryTask parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            NSArray *array = [VRHistoryTaskModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [self.recordModelArray addObjectsFromArray:array];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                self.nodataView.hidden = self.recordModelArray.count > 0;
                [self.tableView reloadData];
                [hud hideAnimated:YES];
                if (array.count == 0) {
                    self.tableView.mj_footer.hidden = YES;
                }else if (array.count < 10){
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }else{
                    [self.tableView.mj_footer endRefreshing];
                }
            });
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
                [self.tableView.mj_footer endRefreshing];
            });
        }
        [self.tableView.mj_header endRefreshing];
    } error:^(NSError * _Nonnull error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
            [hud hideAnimated:YES];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        });
    }];
}


- (void)searchRecordWith:(NSString *)time IsRemoveArray:(BOOL)isRemoveArray
{
    if (isRemoveArray) {
        self.currentPage = 1;
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"UserID"] = [VRUser shareUser].token;
    param[@"time"] = time;
    //    param[@"fIsAreaManage"] = @([VRUser shareUser].fIsAreaManage);
    param[@"page"] = @(self.currentPage++);
    
    if (isRemoveArray) {
        [self.recordModelArray removeAllObjects];
    }
    
    weakify(self)
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    [JKNetworking postWithSign:QueryHistoryTask parameters:param success:^(NSDictionary *responseObject) {
        
        strongify(self)
        NSLog(@"responseObject:%@", responseObject);
        NSInteger code = [responseObject[@"state"] integerValue];
        NSString *msg = responseObject[@"message"];
        
        if (code == 0) {
            
            NSArray *array = [VRHistoryTaskModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            [self.recordModelArray addObjectsFromArray:array];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                self.nodataView.hidden = self.recordModelArray.count > 0;
                [self.tableView reloadData];
                [hud hideAnimated:YES];
                if (array.count == 0) {
                    self.tableView.mj_footer.hidden = YES;
                }else if (array.count > 10){
                    self.tableView.mj_footer.hidden = YES;
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }
            });
        }else if(msg.length > 0){
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:msg];
                [hud hideAnimated:YES];
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
                self.tableView.mj_footer.hidden = YES;
            });
        }
    } error:^(NSError * _Nonnull error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"未知错误"];
            [hud hideAnimated:YES];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            self.tableView.mj_footer.hidden = YES;
        });
    }];
}


#pragma mark - action
- (void)onShowAllBtnClick:(UIButton *)sender
{
    self.searchTime = nil;
    [self getRecordWithIsRemoveArray:YES];
}

- (void)onSearchBtnClick:(UIButton *)sender
{
    [self searchRecordWith:[NSString stringWithFormat:@"%zd", (long)(1900 + self.curSelectedIndex)] IsRemoveArray:YES];
}

- (void)onChoseDateBtnClick:(UIButton *)sender
{
    
//    NSMutableArray *yearArray = [NSMutableArray array];
//    for (int i = 1900; i < 2100; i++) {
//        [yearArray addObject:[NSString stringWithFormat:@"%d年", i]];
//    }
//    self.selectorView.titleArray = [yearArray copy];
    
    [self.chooseDataView showOnWindow];
//    if (self.selectorView.curSelectedIndex == 0) {
//        self.selectorView.curSelectedIndex = 2018 - 1900;
//    }
}


#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.recordModelArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    VRHistoryTaskCell *cell = [VRHistoryTaskCell cellWith:tableView];
    cell.model = self.recordModelArray[indexPath.row % self.recordModelArray.count];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}


#pragma mark - setter && getter
- (VRChooseMonthView *)chooseDataView
{
    if(_chooseDataView == nil){
        
        _chooseDataView = [[VRChooseMonthView alloc] init];
        _chooseDataView.topMargin = 0;
        weakify(self)
        _chooseDataView.sureBlock = ^(NSInteger year, NSInteger month) {
          
            strongify(self)
            NSString *time = [NSString stringWithFormat:@"%zd-%02zd", (long)year, (long)month];
            self.searchTime = time;
            [self searchRecordWith:time IsRemoveArray:YES];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.choseDateBtn setTitle:[NSString stringWithFormat:@"%zd.%02zd", (long)year, (long)month] forState:UIControlStateNormal];
            });
        };
    }
    return _chooseDataView;
}


#pragma mark - lazy
- (UITableView *)tableView
{
    if (_tableView == nil) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT + 70, kScreenWidth, kScreenHeight - NAVIGATION_BAR_HEIGHT - 70) style:UITableViewStylePlain];
        _tableView.backgroundColor = ScrollViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableHeaderView = [[UIView alloc] init];
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
        UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0)];
        _tableView.tableFooterView = view1;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.sectionFooterHeight = 0.01;
        [self.view addSubview:self.tableView];
        //        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        //            make.left.right.bottom.mas_equalTo(self.view);
        //            make.top.mas_equalTo(0);
        //        }];
    }
    return _tableView;
}

- (XNoDataView *)nodataView
{
    if (_nodataView == nil) {
        
        _nodataView = [[XNoDataView alloc] init];
        _nodataView.hidden = YES;
        _nodataView.showText = @"暂无历史任务记录~";
        _nodataView.frame = CGRectMake(0, kScreenHeight * 0.5 - 200, kScreenWidth, 200);
        [self.tableView addSubview:_nodataView];
    }
    return _nodataView;
}



@end
